package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.*;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 明细服务接口实现
 */
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRepository repsitory;
    @Autowired
    private IStrategyCatalogService strategyCatalogService;
    @Autowired
    private IStrategyThemeService strategyThemeService;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        repsitory.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        repsitory.save(strategy);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if (StringUtils.hasLength(qo.getThemeId())) {
            query.addCriteria(Criteria.where("ThemeId").is(qo.getThemeId()));
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, pageable, query, Strategy.class, qo);
    }

    @Override
    public List<Strategy> findByCatalogId(String id) {

        return repsitory.findByCatalogId(id);
    }


    @Override
    //查询某个目的地下的攻略，点击量前3
    public List<Strategy> queryViewnumTop3ByDestId(String destId) {
        //1、查询某个目的地下的攻略
        //2、点击量前3
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        return repsitory.findByDestId(destId, pageable);
    }


    @Override
    public void updateStrategyByVo(StrategyStatisVO vo) {
        if (StringUtils.hasLength(vo.getStrategyId())) {
            Strategy strategy = this.get(vo.getStrategyId());
            strategy.setViewnum(vo.getViewnum());
            strategy.setFavornum(vo.getFavornum());
            strategy.setReplynum(vo.getReplynum());
            strategy.setSharenum(vo.getSharenum());
            strategy.setThumbsupnum(vo.getThumbsupnum());
            this.update(strategy);
        }

    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        //需要在业务层去设置缺失的数据：看自己有什么参数和缺失参数的关系
        //目的地id
        String catalogId = strategy.getCatalogId();//获取分类的id
        StrategyCatalog strategyCatalog = strategyCatalogService.get(catalogId);//获取分类的对象
        strategy.setDestId(strategyCatalog.getDestId());//获得目的地id，设置进去
        //目的地名字
        strategy.setDestName(strategyCatalog.getDestName());//获得目的地name，设置进去
        //分类名称
        strategy.setCatalogName(strategyCatalog.getName());
        //主题名称
        String themeId = strategy.getThemeId();
        StrategyTheme strategyTheme = strategyThemeService.get(themeId);
        strategy.setThemeName(strategyTheme.getName());
        //状态是否是国外
        //通过目的地土司拿到最大的父类，是中国把状态设置成国内
        List<Destination> list = destinationService.queryToasts(strategyCatalog.getDestId());
        if (list != null && list.size() > 0) {
            Destination destination = list.get(0);
            if ("中国".equals(destination.getName())) {
                strategy.setIsabroad(strategy.ABROAD_NO);
            } else {
                strategy.setIsabroad(strategy.ABROAD_YES);
            }
        }


        if (StringUtils.hasLength(strategy.getId())) {
            //维护不需要修改的数据：点赞数等等 //时间也不改
            //查询
            Strategy temp = this.get(strategy.getId());
            //设置（替换）
            strategy.setFavornum(temp.getFavornum());
            strategy.setReplynum(temp.getReplynum());
            strategy.setSharenum(temp.getSharenum());
            strategy.setViewnum(temp.getViewnum());
            strategy.setThumbsupnum(temp.getThumbsupnum());
            strategy.setCreateTime(temp.getCreateTime());
            //更新update
            this.update(strategy);
        } else {
            //save
            //维护创建时间
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }

    }

    @Override
    public List<Strategy> queryByDestName(String destName) {
        return repsitory.findByDestName(destName);
    }


}
